package com.projecetest.educenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.projecetest.commonutils.JwtUtils;
import com.projecetest.commonutils.MD5;
import com.projecetest.educenter.entity.UcenterMember;
import com.projecetest.educenter.mapper.UcenterMemberMapper;
import com.projecetest.educenter.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.projecetest.servicebase.exceptionhandler.TestException;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Captain
 * @since 2021-08-29
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    //登录
    @Override
    public String login(UcenterMember member) {
        //获取登录信息
        String mobile = member.getMobile();
        String password = member.getPassword();

        //判断非空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password))
        {
            throw new TestException(20001,"登录失败！");
        }
        //判断手机号是否正确
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        UcenterMember mobileMember = baseMapper.selectOne(wrapper);
        if (mobileMember == null)
        {
            throw new TestException(20001,"手机号不正确！");
        }
        //判断密码是否正确
        if (!MD5.encrypt(password).equals(mobileMember.getPassword()))
        {
            throw new TestException(20001,"密码不正确！");
        }
        //判断用户是否禁用
        if (mobileMember.getIsDisabled())
        {
            throw new TestException(20001,"用户被禁用！");
        }

        //登录成功
        String jwtToken = JwtUtils.getJwtToken(mobileMember.getId(), mobileMember.getNickname());
        return jwtToken;
    }

    @Override
    public void register(UcenterMember member) {
        //获取注册数据
        String mobile = member.getMobile();
        String nickname = member.getNickname();
        String password = member.getPassword();
        //判断非空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(password))
        {
            throw new TestException(20001,"注册失败！");
        }

        //手机号不能重复
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0)
        {
            throw new TestException(20001,"注册失败！");
        }
        //数据添加到数据库
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setMobile(mobile);
        ucenterMember.setNickname(nickname);
        ucenterMember.setPassword(MD5.encrypt(password));
        ucenterMember.setIsDisabled(false);
        baseMapper.insert(ucenterMember);
    }
}
